import pytest
import os
import sys
import pymysql
from pymysql.cursors import DictCursor
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../')))

from public.Logger import Logger
from public.Tools import get_log_conf, get_project_conf
from public.ExceptionSet import ProjectNotFound

@pytest.fixture(scope="module", autouse=True)
def project_name(request):
    return os.path.basename(os.path.dirname(request.path))


@pytest.fixture(scope="module", autouse=True)
def logger(project_name):
    loggerObj = Logger(project_name, get_log_conf())
    yield loggerObj

    # TODO: 将日志进行压缩、打包、上传


@pytest.fixture(scope="module", autouse=True)
def project_config(project_name, logger):
    config = get_project_conf()
    if project_name in config.keys():
        return config[project_name]
    else:
        raise ProjectNotFound(project_name, "projectConf.yaml文件中必须包含项目同名配置")


@pytest.fixture(scope="module", autouse=True)
def db(project_config):
    db_connect = pymysql.Connect(
        **project_config['db_connect'],
        cursorclass=DictCursor
    )
    yield db_connect
    db_connect.close()


# @pytest.hookimpl(hookwrapper=True, tryfirst=True)
# def pytest_runtest_makereport(item, call):
#     out = yield
#     report = out.get_result()
#
#     print('测试报告：%s' % report)
#     print('步骤：%s' % report.when)
#     print(('运行结果: %s' % report.outcome))